package com.uyayo.oms.system.controller;


import com.uyayo.framework.common.annotation.MethodName;
import com.uyayo.framework.common.exception.CodeMultipleException;
import com.uyayo.framework.common.exception.ParentNotFoundException;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.message.model.Tree;
import com.uyayo.framework.common.util.CodeUtil;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.oms.system.constants.MethodConstants;
import com.uyayo.oms.system.vo.SysOrganizationVO;
import com.uyayo.system.authority.entity.SysOrganization;
import com.uyayo.system.authority.entity.SysOrganizationResource;
import com.uyayo.system.authority.entity.SysUser;
import com.uyayo.system.authority.service.SysOrganizationService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 
 * <p>
 * Title: OrganizationController
 * </p>
 * <p>
 * Description:机构的controller
 * </p>
 * <p>
 * Company: www.lelekeji.com
 * </p>
 * 
 * @author 乐乐科技.胡逢君
 * @date 2015-4-13下午4:03:35
 * @version 1.0
 */
@Controller
@RequestMapping("/system/authority/organization")
public class SysOrganizationController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
    SysOrganizationService organizationService;

	@Autowired
	private ParamBiz paramBiz;

	private  final MessageSource messageSource;

	public SysOrganizationController(MessageSource messageSource) {
		this.messageSource = messageSource;
	}

	/**
	 * 进入机构主页面
	 */
	@RequestMapping("index")
	@RequiresPermissions("system:authority:organization:index")
	@MethodName(value="系统管理->权限管理->机构管理")
	public String index(Model model, String parentId) {
		model.addAttribute("parentId",parentId);
		return paramBiz.getManagerTemplatesPrefix()+"system/authority/organization/index";
	}

	/**
	 * 获得资源treeGrid
	 */
	@ResponseBody
	@RequestMapping("treeGrid")
	@RequiresPermissions("system:authority:organization:grid")
	@MethodName(coding= MethodConstants.ORGANIZATION_SEARCH_CODING, value=MethodConstants.ORGANIZATION_SEARCH,type=2)
	public List<SysOrganization> treeGrid(SysOrganization organization) {
		return organizationService.organizationTreeGrid(organization);
	}


	/**
	 * 查看机构信息
	 */
	@RequestMapping("view")
	@RequiresPermissions("system:authority:organization:view")
	@MethodName(value="系统管理->权限管理->机构管理->查看机构",type=2)
	public ModelAndView view(ModelAndView modelAndView,String id) {
		SysOrganization organization = organizationService.selectOrganizationById(id);
		modelAndView.addObject("sysOrganization",organization);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/authority/organization/view");
		return modelAndView;
	}

	@ResponseBody
	@RequestMapping(value = "add", method = RequestMethod.GET)
	@RequiresPermissions("system:authority:organization:add")
	public ModelAndView add(ModelAndView modelAndView) {
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/authority/organization/add");
		return modelAndView;
	}
	
	/**
	 * 保存一个机构
	 */
	@ResponseBody
	@RequestMapping("add")
	@RequiresPermissions("system:authority:organization:add")
	@MethodName(value="系统管理->权限管理->机构管理->添加机构",type=2)
	public Result add(@Validated SysOrganizationVO sysOrganizationVO , Errors errors, HttpServletRequest request) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			SysOrganization sysOrganization = new SysOrganization();
			sysOrganization.setId(CodeUtil.getTimeSequenceAsRandomBigCode());
			sysOrganization.setCode(sysOrganizationVO.getCode());
			sysOrganization.setName(sysOrganizationVO.getName());
			sysOrganization.setType(sysOrganizationVO.getType());
			sysOrganization.setAddress(sysOrganizationVO.getAddress());
			sysOrganization.setParentId(sysOrganizationVO.getParentId());
			sysOrganization.setHasChildren(false);
			sysOrganization.setStatus(sysOrganizationVO.getStatus());
			sysOrganization.setSeq(sysOrganizationVO.getSeq());
			sysOrganization.setCreatedBy(sysUser.getLoginname());
			sysOrganization.setCreatedTime(new Date());
			organizationService.saveOrganization(sysOrganization);
		}catch(Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(500,message);
		}
		String message = messageSource.getMessage("save.success",new Object[]{}, request.getLocale());

		return Result.successAndMsg(message);
	}


	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.GET)
	@RequiresPermissions("system:authority:organization:update")
	public ModelAndView update(ModelAndView modelAndView,String id) {
		SysOrganization sysOrganization = organizationService.selectOrganizationById(id);
		modelAndView.addObject("sysOrganization",sysOrganization);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/authority/organization/update");
		return modelAndView;
	}

	/**
	 * 更新机构
	 */
	@ResponseBody
	@RequestMapping("update")
	@RequiresPermissions("system:authority:organization:update")
	@MethodName(value="系统管理->权限管理->机构管理->修改机构",type=2)
	public Result updateOrganization(@Validated SysOrganizationVO sysOrganizationVO , Errors errors, HttpServletRequest request) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}
			if (StringUtils.isEmpty(sysOrganizationVO.getId())) {
				String message = messageSource.getMessage("parameter.error",new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.build(400,message);
			}

			if (sysOrganizationVO.getParentId() != null && Objects.equals(sysOrganizationVO.getId(), sysOrganizationVO.getParentId())) {
				String message = messageSource.getMessage("parent.self.error",new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.build(400,message);
			}

			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();

			SysOrganization sysOrganization = new SysOrganization();

			sysOrganization.setId(sysOrganizationVO.getId());
			sysOrganization.setCode(sysOrganizationVO.getCode());
			sysOrganization.setName(sysOrganizationVO.getName());
			sysOrganization.setParentId(sysOrganizationVO.getParentId());
			sysOrganization.setAddress(sysOrganizationVO.getAddress());
			sysOrganization.setSeq(sysOrganizationVO.getSeq());
			sysOrganization.setDescription(sysOrganizationVO.getDescription());
			sysOrganization.setModifiedBy(sysUser.getLoginname());
			sysOrganization.setModifiedTime(new Date());
			sysOrganization.setRemark(sysOrganizationVO.getRemark());
			sysOrganization.setStatus(sysOrganizationVO.getStatus());
			int updateCount = organizationService.updateOrganization(sysOrganization);
			if(updateCount<=0){
				String message = messageSource.getMessage("save.fail",new Object[]{}, request.getLocale());
				logger.info(message);
				return Result.build(400,message);
			}
			String message = messageSource.getMessage("save.success",new Object[]{}, request.getLocale());

			return Result.success(200,message);

		} catch (ParentNotFoundException e){
			String message = messageSource.getMessage("parent.not.found.error",new Object[]{}, request.getLocale());
			logger.info(message,e.getMessage());
			return Result.build(400,message);
		} catch (CodeMultipleException e){
			String message = messageSource.getMessage("code.multiple.error",new Object[]{}, request.getLocale());
			logger.info(message,e.getMessage());
			return Result.build(400,message);
		} catch(Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.build(500,message);
		}
	}

	/**
	 * 删除机构
	 */
	@ResponseBody
	@RequestMapping("delete")
	@RequiresPermissions("system:authority:organization:delete")
	@MethodName(value="系统管理->权限管理->机构管理->删除机构",type=2)
	public Result deleteOrganization(String id,HttpServletRequest request) {
		try {
			if (StringUtils.isEmpty(id)) {
				String message = messageSource.getMessage("parameter.error",new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.build(400,message);
			}
			int deleteCount = organizationService.deleteOrganization(id);
			if(deleteCount<=0){
				String message = messageSource.getMessage("delete.fail",new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.build(400,message);
			}
		} catch(Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.build(500,message);
		}
		String message = messageSource.getMessage("delete.success",new Object[]{}, request.getLocale());
		logger.info(message);
		return Result.success(200,message);
	}
	
	/**
	 * 获得机构tree，也用于获得上级机构tree
	 */
	@ResponseBody
	@RequestMapping("getSysOrganizationTree")
	public List<Tree> getSysOrganizationTree(HttpServletResponse response,HttpServletRequest request,SysOrganization organization) {
		List<SysOrganization> organizations = organizationService.selectOrganizationAll(organization);
		List<Tree> tree = new ArrayList<Tree>();
		for (SysOrganization organization_ : organizations) {
			Tree node = new Tree();
			node.setId(organization_.getId());
			node.setPid(organization_.getParentId());
			node.setIconCls(organization_.getIconCls());
			node.setName(organization_.getName());
			tree.add(node);
		}
		return tree;
	}
	
	
	
	/**
	 * 进入机构表单
	 */
	@RequestMapping("doNotNeedSecurity_grantForm")
	public ModelAndView organizationGrant_form(ModelAndView modelAndView,String id) {
		modelAndView.addObject("id",id);
		modelAndView.setViewName("oms/system/authority/organizationGrant");
		return modelAndView;
	}
	
	
	/**
	 * 根据机构id获得资源
	 */
	@ResponseBody
	@RequestMapping("doNotNeedSecurity_findOrganizationResources")
	public List<SysOrganizationResource> doNotNeedSecurity_findOrganizationResources(HttpServletResponse response, HttpServletRequest request, String organizationId) {
		
		List<SysOrganizationResource> organizationResources = new ArrayList<>();
		try {
			organizationResources = organizationService.findOrganizationResources(organizationId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return organizationResources;
	}
	
	
	/**
	 * 获得当前用户的机构
	 */
	@ResponseBody
	@RequestMapping("findOrganizationByUserId")
	public List<SysOrganization> findOrganizationByUserId(HttpServletResponse response,HttpServletRequest request,String userId) {
		List<SysOrganization> organizations = organizationService.findOrganizationByUserId(userId);
		return organizations;
	}
	
	/**
	 * 授权资源
	 */
	@ResponseBody
	@RequestMapping("grant")
	@MethodName(value="系统管理->权限管理->机构管理->授权资源",type=2)
	public Result grantOrganizationResource(HttpServletResponse response,HttpServletRequest request,String ids,String organizationId) {
		Result customResult;
		try {
			customResult = organizationService.grantOrganizationResource(ids,organizationId);
		} catch (Exception e) {
			customResult = new Result(500,"保存失败");
		}
		return customResult;
	
	}
}
